package com.example.producer.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class Sender {

    @Autowired
    private AmqpTemplate amqpTemplate;

    public String send(String context) {
        log.info("send time：" + new Date());
        amqpTemplate.convertAndSend("work.queue", context);
        return "success";
    }
    public String sendTTLQueuenMsg(String context) {
        log.info("sendTTLMsg time：" + new Date());
        amqpTemplate.convertAndSend("TTLDirectQueue", context);
       /* MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setExpiration("8000");//8m
                return message;
            }
        };*/
       // amqpTemplate.convertAndSend("TTLDirectQueue", (Object) context, messagePostProcessor);
        return "success";
    }


    public String sendDirectMessage(String messageData) {
        String messageId = String.valueOf(UUID.randomUUID());
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String, Object> map = new HashMap<>();
        map.put("messageId", messageId);
        map.put("messageData", messageData);
        map.put("createTime", createTime);
        //将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
        String routingKey = "TestDirectRouting";
        amqpTemplate.convertAndSend("TestDirectExchange", routingKey, map);
        return "success";
    }

    /*订阅模型-Fanout*/
    public void fanout() {
        String msg = "订阅模式";
        for (int i = 0; i < 10; i++) {
            // 这里注意细节，第二个参数需要写，否则第一个参数就变成routingKey了
            amqpTemplate.convertAndSend("test.fanout.exchange", "", msg + i);
        }
    }
    /* 订阅模型-Topic (主题模式)*/
    public void topic() {
        amqpTemplate.convertAndSend("test.topic.exchange", "person.insert", "增加人员");
        amqpTemplate.convertAndSend("test.topic.exchange", "person.delete", "删除人员");
        amqpTemplate.convertAndSend("test.topic.exchange", "money.insert", "加钱");
        amqpTemplate.convertAndSend("test.topic.exchange", "money.delete", "减钱");
    }
}
